# -*-coding:utf-8 -*-
'''
Created on 2011-10-10

@author: tony.li.fly@gmail.com
'''
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.utils import simplejson as json
from xyh.oa.models import Role,MenuType,Menu

def toAddRole(request):
    return render_to_response('role/add.html')

def addRole(request):
    role = Role(name=request.POST['name'],description=request.POST['description'])
    role.save()
    return HttpResponse()
    
def listRoles(request):
    roles = Role.objects.all();
    rolesJson = {'roles':[]};
    for role in roles:
        rolesJson['roles'].append({'id':role.id,'name':role.name,'description':role.description})
    return HttpResponse(json.dumps(rolesJson))

def delRole(request,role_id):
    p = Role.objects.get(pk=role_id)
    p.delete()
    return HttpResponse()

def updateRole(request):
    role = Role.objects.get(pk = request.POST['id'])
    role.name = request.POST['name']
    role.description = request.POST['description']
    role.save()
    return HttpResponse()

def menuConfig(request):
    #
    roleId = request.POST['roleId']
    role = Role.objects.get(pk=roleId)
    checked_menus = []
    for i in role.menus.all():
        checked_menus.append(i.id)
    
    
    
    allTypes = MenuType.objects.all();
    allTypesJSON = []
    for _type in allTypes:
        _typeJSON = {'name':_type.name}
        _menus = []
        for _menu in _type.menu_set.all():
            if checked_menus.__contains__(_menu.id):
                _menus.append({"id":_menu.id,"name":_menu.name,"checked":True})
            else:
                _menus.append({"id":_menu.id,"name":_menu.name})
        _typeJSON["menus"] = _menus
        allTypesJSON.append(_typeJSON)
    return HttpResponse(json.dumps(allTypesJSON))

def resetMenuConfig(request):
    roleId = request.POST['id']
    menus = request.POST.getlist('menus')
    role = Role.objects.get(pk=roleId)
    role.menus.clear()
    for menu_id in menus:
        role.menus.add(Menu.objects.get(pk=menu_id))
        
    return HttpResponse()
    
    